var express = require('express');
var router = express.Router();
var WebTools = require('../../../../common/module/webtools');
var DB = require("../../../../common/module/data-base");

module.exports = class extends baseController{
    constructor(){
        super();
        this.paramsLogic=this.loadLogic('iframe/params');
        this.router.post('/getItems',this.getItems.bind(this));
        this.router.post('/getItem',this.getItem.bind(this));
        this.router.post('/edit',this.edit.bind(this));
        this.router.post('/del',this.del.bind(this));
        return this.router;
    }

    async getItems(req,res){
        let Result={};
        try{
            let queryModel={
                CurPage:req.body.CurPage ? Number(req.body.CurPage) : 1,
                PageSize:req.body.PageSize ? Number(req.body.PageSize) : 20,
                Sort:req.body.Sort ? req.body.Sort : "ConfigKey|asc",
                ConfigKey:req.body.ConfigKey || ''
            }
            let ret= await this.paramsLogic.getItems(queryModel);
            Result=this.Success(1,ret);
        }
        catch(err){
            Result=this.Error('查询失败',err);
        }
        res.json(Result);
    }

    async getItem(req,res){
        let Result={};
        let model={};
        try{
            let key = req.body.ConfigKey || '';
            if(key!=''){
                 model= await this.paramsLogic.getItem(key);
                if(!model){
                    Result=this.Error('记录不存在');
                    return res.json(Result);
                }
            }else{
                model = {};
            }
        
            Result=this.Success(1,model);
        }
        catch(err){
            Result=this.Error('查询失败',err);
        }
        res.json(Result);
    }

    async edit(req,res){
        let Result={};
        try{
         
            let ret= await this.paramsLogic.insertOrUpdate(req.body);
            if(ret){
                Result=this.Success(1,ret);
            }else{
                Result=this.Error('记录更新失败');
            }
           
        }
        catch(err){
            Result=this.Error('记录更新失败',err);
        }
        res.json(Result);
    }

    async del(req,res){
        let Result={};
        try{
            let keys = req.body.keys;
            let ret= await this.paramsLogic.del(keys);
            Result=this.Success(1);
        }
        catch(err){
            Result=this.Error('记录删除失败',err);
        }
        res.json(Result);
    }


};







